<?php


namespace app\common\model\delivery;

use app\common\model\BaseModel;
use app\common\model\store\order\StoreOrder;
use app\common\model\store\order\StoreOrderStatus;
use app\common\model\system\merchant\Merchant;
use crmeb\services\DeliverySevices;

class DeliveryExpressOrder extends BaseModel
{

    public static function tablePk(): string
    {
        return 'delivery_express_order_id';
    }

    public static function tableName(): string
    {
        return 'delivery_express_order';
    }

    public function merchant()
    {
        return $this->hasOne(Merchant::class, 'mer_id','mer_id');
    }

    public function station()
    {
        return $this->hasOne(DeliveryExpressStation::class, 'station_express_id','station_express_id');
    }

    public function storeOrder()
    {
        return $this->hasOne(StoreOrder::class, 'order_id','order_id');
    }

    public function storeOrderStatus()
    {
        return $this->hasMany(StoreOrderStatus::class, 'order_id','order_id')->order('change_time DESC');
    }


    public function searchKeywordAttr($query,$value)
    {
        $query->whereLike('order_sn|from_address',"%{$value}%");
    }

    public function searchMerIdAttr($query,$value)
    {
        $query->where('mer_id',$value);
    }

    public function searchStationIdAttr($query,$value)
    {
        $query->where('station_express_id',$value);
    }
    public function searchOrderIdAttr($query,$value)
    {
        $query->where('order_id',$value);
    }
    public function searchSnAttr($query,$value)
    {
        $query->where('order_sn',$value);
    }
    public function searchDateAttr($query,$value)
    {
        getModelTime($query, $value);
    }
    public function searchOrderSnAttr($query,$value)
    {
        $ids = StoreOrder::whereLike('order_sn',"%{$value}%")->column('order_id');
        $query->whereIn('order_id', $ids);
    }

    public function getOrderExpressNumber($order_sn){
        $sn = explode('-', $order_sn)[0];
        return $sn . ('-d' . ($this->where('order_sn','like', $sn.'%')->count() + 1));
    }
}
